package servlet.reader;

import net.sf.json.JSONObject;
import service.reader.AdminService;
import service.reader.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;

/**
 * AdminLogin
 *
 * @author ChenYanMei
 * @version 2023/8/29
 */
@WebServlet("/AdminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    AdminService service = new AdminServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // ①设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/JSON;charset=utf-8");
        resp.setCharacterEncoding("UTF-8");

        PrintWriter out = resp.getWriter();

        String userName = req.getParameter("username");
        String password = req.getParameter("password");

        // 设置响应map
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        String result = null;
        try {
            result = service.login(userName, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result != null && result.equals("1")) {
            HttpSession session = req.getSession();
            session.setAttribute("admin", userName);
            hashMap.put("code", 0);
            hashMap.put("msg", "登录成功");
            hashMap.put("url", req.getContextPath() +"/admin/index.jsp");
        }else {
            hashMap.put("code", 1);
            hashMap.put("msg", result);
        }

        JSONObject json = JSONObject.fromObject(hashMap);
        out.write(json.toString());

    }

}
